package gest;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Farmacia_Impl extends UnicastRemoteObject implements Farmacia {
	
	private int nlicenca;
	private String nome;
	private String morada;
	private int nif;
	private int id;
	public static Connection conn;

	public Farmacia_Impl(int nlicenca) throws RemoteException {
		this.nlicenca = nlicenca;
		Statement st;
		ResultSet rs;
		if (conn == null)
			conn = DBConnection.get_conn();
		try {
			st = conn.createStatement();
			String query = "select nome, morada, nif, idFarm from Farmacias where licenca="
					+ nlicenca;
			rs = st.executeQuery(query);
			if (rs.first()) {
				this.nome = rs.getString(1);
				this.morada = rs.getString(2);
				this.nif = rs.getInt(3);
				this.id = rs.getInt(4);
			} else {
					st.execute("insert into Farmacias (licenca) values ("
						+ nlicenca + ")", st.RETURN_GENERATED_KEYS);
					rs = st.getGeneratedKeys();
					rs.first();
					this.id = rs.getInt(1);
					this.nome = "Nao inserido";
					this.morada = "Nao inserido";
					this.nif = -1;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public int get_nlicenca() throws RemoteException {
		return nlicenca;
	}

	public String get_nome() throws RemoteException {
		return this.nome;
	}

	public String get_morada() throws RemoteException {
		return this.morada;
	}

	public int get_nif() throws RemoteException {
		return this.nif;
	}

	public boolean set_nome(String nome) throws RemoteException {
		if (!this.nome.equals(nome)){
			if (update_field("nome", nome)) {
			this.nome = nome;
			}
		}
		return true;
	}

	public boolean set_morada(String morada) throws RemoteException {
		if (!this.morada.equals(morada)){
			if(update_field("morada", morada)){
				this.morada = morada;
			}
		}
		return true;
	}

	public boolean set_nif(int nif) throws RemoteException {
		if (this.nif!=nif){			
			if(this.update_field("nif", nif)){
				this.nif = nif;
			}
		}
		return true;
	}
	
	private boolean update_field(String field, Object Value) {
		Statement st;
		try {
			if (conn == null)
				conn = DBConnection.get_conn();
			st = conn.createStatement();
			String query = "update Farmacias set " + field + "='"
					+ Value.toString() + "' where licenca=" + this.nlicenca;
			st.execute(query);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return true;
	}
}
